<template>
  <div class="app-container">
   
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入用户名称" v-model="listQuery.name"></el-input>
      <el-button class="filter-item" type="primary" style="float:right;"  icon="el-icon-edit"  @click="handleCreate">新增</el-button>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="func()">跳转</el-button>
      <el-button class="filter-item" type="primary" icon="document" @click="handleDownload" :loading="downloadLoading"> 导出EXCEL</el-button>
      <el-button class="filter-item" type="primary" style="float:right;"  icon="el-icon-edit"  @click="uploadexcel">导入EXCEL</el-button>
      <router-link to="/form/index">
       <button class="btn btn-default">点击跳转</button>
      </router-link>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" label="行号" width="65">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="日期">
        <template slot-scope="scope">
          <span>{{scope.row.gmtCreate | formatDatetime}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="用户名称">
        <template slot-scope="scope">
          <span class="link-type" >{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="登入名称">
        <template slot-scope="scope">
          <span class="link-type" >{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="备注">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
         <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情</el-button>
         <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
         <el-button type="warning" size="mini" @click="distributionRole(scope.row)">角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
        <el-input type="hidden" v-model="temp.id"></el-input>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="登入名称" prop="username">
          <el-input v-model="temp.username"></el-input>
        </el-form-item>
        <el-form-item label="登入密码" prop="password">
          <el-input type="password" v-model="temp.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="cpassword">
          <el-input type="password" v-model="temp.cpassword"></el-input>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">cancel</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">confirm</el-button>
        <el-button v-else type="primary" @click="updateData">confirm</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogPvVisible">
      <template>
        <el-transfer v-model="distributionRoles" :data="roles"></el-transfer>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Close</el-button>
        <el-button type="primary" @click="saveUcUserRoles">save</el-button>
      </span>
    </el-dialog>

    <el-dialog title="detail" :visible.sync="dialogDetailVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
        <el-input type="hidden" v-model="temp.id"></el-input>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="登入名称" prop="username">
          <el-input v-model="temp.username"></el-input>
        </el-form-item>
        <el-form-item label="登入密码" prop="password">
          <el-input type="password" v-model="temp.password"></el-input>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogDetailVisible = false">CLOSE</el-button>
      </span>
    </el-dialog>
    
    <el-dialog title="上传EXCEL" :visible.sync="dialogUploadVisible">
      <template>
        <div class="app-container">
          <upload-excel-component @on-selected-file='selected'></upload-excel-component>
          <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
            <el-table-column v-for='item of tableHeader' :prop="item" :label="item" :key='item'>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadSave()">SAVE</el-button>
        <el-button type="primary" @click="dialogPvVisible = false">Close</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchUserList, getUcUser, createUcUser, updateUcUser, getRolesByUserId, saveUcUserRoles } from '@/api/ucUser'
import { getRolesList } from '@/api/ucRole'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime, formatDate, formatDatetime  } from '@/utils'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
export default {
  name: 'ucUser',
  components: { UploadExcelComponent },
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      filename: '',
      autoWidth: true,
      downloadLoading: false,
      tableData: [],
      tableHeader: [],
      listQuery: {
        name: '',
        page: 1,
        limit: 20,
        username: '',
        sort: '+id'
      },
      temp: {
        id: '',
        name: '',
        username: '',
        password: '',
        cpassword:'',
        remark: '',
        state:0,
        isDeleted: 0,
        gmtCreate: null,
        gmtModified: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      dialogDetailVisible:false,
      dialogUploadVisible:false,
      pvData: [],
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'change' }],
        username: [{ required: true, message: 'username is required', trigger: 'change' }],
        password: [{ required: true, message: 'password is required', trigger: 'change' }],
        cpassword: [{ required: true, message: 'cpassword is required', trigger: 'change' }]
      },
      roles: [],
      distributionRoles: []
    }
  },
  filters: {
    formatDate(time) {
       var date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm');
    },
    formatDatetime(time){
      return formatDatetime(time);
    }      
  },
  created() {
    this.getList()
    this.roles = this.getAllRoles()
  },
  methods: {
    getList() {
      this.listLoading = true
      const param = {
        'body': {
          	"ucUserDTO":{
            "name":this.listQuery.name,
          },
          "pageInfo":{
            "page":this.listQuery.page,
            "pageSize":this.listQuery.limit
          }
        }
      }
      fetchUserList(param).then(response => {
        this.list = response.body.ucUserDTOList
        this.total = response.body.pageInfo.rowCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
          id: '',
          name: '',
          username: '',
          password: '',
          remark: '',
          state:0,
          isDeleted: 0,
          gmtCreate: null,
          gmtModified: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const data = {
            'body': {
              "ucUserDTO":{
                "name":this.temp.name,
                "username":this.temp.username,
                "password":this.temp.password,
                "isDeleted":0,
                "state":0,
                "remark":this.temp.remark
              }
            }
          }
          // this.temp.appId = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.flag = 0
          createUcUser(data).then(response => {
            this.list.unshift(response.body.ucUserDTO)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.utime = new Date(this.temp.timestamp)
      this.temp.cpassword = this.temp.password
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          const data = {
            'body': {
              "ucUserDTO":{
                "id":this.temp.id,
                "name":this.temp.name,
                "username":this.temp.username,
                "password":this.temp.password,
                "isDeleted":0,
                "state":0,
                "remark":this.temp.remark
              }
            }
          }
          updateUcUser(data).then(response => {
            const ucUserDTO = response.body.ucUserDTO;
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, ucUserDTO)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      
      const data = {
          'body': {
              "ucUserDTO":{
                "id":row.id,
                "isDeleted":1
              }
            }
          }
          updateUcUser(data).then(response => {
            const ucUserDTO = response.body.ucUserDTO;
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, ucUserDTO)
                break
              }
            }
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleDetail(row) {   
        this.temp = Object.assign({}, row) // copy obj
        this.dialogDetailVisible = true
    },
    distributionRole(row){
        this.temp = Object.assign({}, row) // copy obj
        const data = {
          'body': {
              "ucUserDTO":{
                "id":row.id,
              }
            }
          }
          getRolesByUserId(data).then(response => {
            const ucUserDTO = response.body.ucUserDTO;
            this.distributionRoles = ucUserDTO.roleIds;
          })

        this.dialogPvVisible = true
    },
    func(){
        // this.$router.push({name: '/form/index',params:{ id:'1'}});
        this.$router.push({path: '/form/index',query:{ id:'2'}});
    },
    getAllRoles(){
      const param = {
        'body': {
          "ucRoleDTO":{
            "name":'',
          }
        }
      }
      let dataroles = []
      getRolesList(param).then(response => {
          
          let roleList = response.body.ucRoleDTOList
          roleList.forEach((role, index) => {
            dataroles.push({
              label: role.name,
              key: role.id
            });
          })
      })
      return dataroles;
    },
    saveUcUserRoles(){
      const param = {
        'body': {
          "ucUserDTO":{
            "id":this.temp.id,
			      "roleIds": this.distributionRoles
          }
        }
      }
      saveUcUserRoles(param).then(response => {
          this.dialogPvVisible = false;
           this.$notify({
            title: '成功',
            message: '更新角色成功',
            type: 'success',
            duration: 2000
          })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['NAME', 'USERNAME', 'REMARK', 'gmtCreate']
        const filterVal = ['name', 'username', 'remark', 'gmtCreate']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'user',
          autoWidth: this.autoWidth
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    selected(data) {
      this.tableData = data.results
      this.tableHeader = data.header
    },
    uploadexcel() {
      this.dialogUploadVisible = true
    },
    uploadSave() {
      this.$notify({
        title: '成功',
        message: '功能未开放！',
        type: 'success',
        duration: 2000
      })
    }
  }
}
</script>
